package com.lion.repository.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * 
 * @ClassName: ProcessDefineController
 * @Description: 流程定义controller
 * @author Administrator
 * @date 2018年7月17日
 *
 */
@RestController
@RequestMapping("/repository/model")
public class ModelController {

	@Autowired
	RepositoryService repositoryService;

	/**
	 * 
	 * @Description: 流程初始化 @throws
	 */
	@RequestMapping("/init")
	public void init(HttpServletRequest request, HttpServletResponse response) {
		try {

			ObjectMapper objectMapper = new ObjectMapper();
			ObjectNode editorNode = objectMapper.createObjectNode();
			editorNode.put("id", "canvas");
			editorNode.put("resourceId", "canvas");
			ObjectNode stencilSetNode = objectMapper.createObjectNode();
			stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
			editorNode.set("stencilset", stencilSetNode);
			Model modelData = repositoryService.newModel();

			ObjectNode modelObjectNode = objectMapper.createObjectNode();
			modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, "新建流程");
			modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1.0);
			String description = "新流程初始化";
			modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
			modelData.setMetaInfo(modelObjectNode.toString());
			modelData.setName("新建流程");
			modelData.setKey("lion_bpm");

			// 保存模型
			repositoryService.saveModel(modelData);
			repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
			response.sendRedirect(request.getContextPath() + "/activiti/modeler.html?modelId=" + modelData.getId());

		} catch (Exception e) {
			System.out.println("创建模型失败：");
		}
	}
	
	/**
	 * 
	 * @Title: getModelListByPage
	 * @Description: 获取未发布的model列表
	 */
	@PostMapping("/getModelListByPage")
	public List<Model> getModelListByPage(int start, int size ) {

		List<Model> modelList = repositoryService.createModelQuery()
				.notDeployed()
				.orderByCreateTime().desc()
				.listPage(start, size);
		return modelList;
	}
	

	
	@PostMapping("/deploy")
	public String deploy(String modelId) {

		Model modelData = repositoryService.getModel(modelId);
		byte[] mes = repositoryService.getModelEditorSource(modelId);

		ObjectNode modelNode = null;
		try {
			modelNode = (ObjectNode) new ObjectMapper().readTree(mes);
		} catch (IOException e) {
			e.printStackTrace();
		}

		BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
		byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(model);
		String processName = modelData.getName() + ".bpmn20.xml";
		String text = "";
		try {
			text = new String(bpmnBytes, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		Deployment deployment = repositoryService.createDeployment().name(modelData.getName())
				.addString(processName, text).deploy();

		return deployment.getId();
	}
}
